import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { login, getUserInfo } from '@/api/auth'

export const useUserStore = defineStore('user', () => {
  const user = ref(null)
  const token = ref(localStorage.getItem('token') || '')

  const isLoggedIn = computed(() => !!token.value)
  const isAdmin = computed(() => user.value?.role === 'admin')

  // 登录
  const loginUser = async (credentials) => {
    try {
      const response = await login(credentials)
      token.value = response.data.token
      user.value = response.data.user
      localStorage.setItem('token', token.value)
      return response.data
    } catch (error) {
      throw error
    }
  }

  // 登出
  const logoutUser = () => {
    user.value = null
    token.value = ''
    localStorage.removeItem('token')
  }

  // 检查登录状态
  const checkLoginStatus = async () => {
    if (token.value) {
      try {
        const response = await getUserInfo()
        user.value = response.data
      } catch (error) {
        logoutUser()
      }
    }
  }

  return {
    user,
    token,
    isLoggedIn,
    isAdmin,
    loginUser,
    logoutUser,
    checkLoginStatus
  }
})
